package com.heima.search.service.impl;

import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleSearchRepository;
import com.heima.search.service.IArticleSearchService;
import com.heima.search.service.IUserSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleSearchRepository repository;

    @Autowired
    private IUserSearchService userSearchService;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        // 根据前端传递的关键字来查询
        // 在es中进行查询
        // 构建分页条件  参数 1 当前页(从0开始) 2 每页条数  3 排序方向  4 排序字段,可以加多个字段
        Pageable page = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.Direction.DESC, "publishTime");
        // 分页查询
        QueryBuilder query = QueryBuilders.matchQuery("title", dto.getSearchWords());
        Page<ApArticleSearch> searchPage = repository.search(query, page);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize()
                , searchPage.getTotalElements(), searchPage.getContent());

        // 异步保存搜索记录
        User user = AppThreadLocalUtil.get();
        Integer userId = null;
        if (user != null) {
            userId = user.getUserId();
        }
        userSearchService.saveRecord(dto.getSearchWords(), userId, dto.getEquipmentId());
        System.out.println(Thread.currentThread().getName() + "调用异步完成..." + new Date());
        return result;
    }
}
